package com.mike.bdb.ui.provider.table;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mike.bdb.manager.DBManager;
import com.mike.bdb.util.DataCurrent;
import com.mike.bdb.util.ReflectUtil;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.SecondaryIndex;

public class MikeSecondaryTableContentProvider implements IStructuredContentProvider {

	private static final Logger LOG = LoggerFactory.getLogger(MikeSecondaryTableContentProvider.class);
	
	private String pkey;
	private String skName;
	private String keyContext;
	
	@Override
	public Object[] getElements(Object inputElement) {
		Object[] result = null;
		if(null == pkey 
				|| null == skName
				|| null == keyContext) return result;
		
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		if(null == curStoreClazz) return result;
		
		Class<Object> classBy = ReflectUtil.getClassBy(curStoreClazz);
		if(null == classBy) return result;
		
		Class pkClass = ReflectUtil.getPKClass(classBy);

		skName = skName.substring(0, 1).toLowerCase() + skName.substring(1, skName.length());
		
		Class skClass = ReflectUtil.getSKClass(classBy, skName);

		SecondaryIndex store = DBManager.getInstance().getSKStore(pkClass, classBy, skClass, skName);

		EntityCursor entities = store.subIndex(ReflectUtil.getRealType(skClass, keyContext)).entities();
		
		PageInfo secondaryPageInfo = DataCurrent.getInstance().getSecondaryPageInfo();
		
		int index = 0;
		
		List<Object> re = new ArrayList<Object>();
		
		for (Object o : entities) {
			
			//1.不足
			if(index < secondaryPageInfo.fromInt()) {
				++index;
				continue;
			}
			
			//2.命中 
			if(index >= secondaryPageInfo.fromInt() && index < secondaryPageInfo.toInt()) {
				re.add(o);
				++index;
			}
			
			//3.越界
			if(index >= secondaryPageInfo.toInt()) {
				++index;
				break;
			}
		}
		
		if(LOG.isDebugEnabled()) {
			LOG.debug("size:" + re.size());
		}
		
		entities.close();
		return re.toArray();
	}
	
	@Override
	public void dispose() {
		
	}

	@Override
	public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
		
	}

	public void setSee(String pkey, String skName, String keyContext) {
		this.pkey = pkey;
		this.skName = skName;
		this.keyContext = keyContext;
	}

}
